import React, { Fragment, useState, useEffect, useCallback } from 'react';
import { Form, Input, Button, DatePicker } from 'antd';
import { history } from 'umi';
import { eventTrack } from '@/utils/track';
import { groupBy } from 'lodash';
import SimpleDataTable from '@/components/DataTable2/SimpleDataTable';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import QuickEntry from '@/components/QuickEntry';
import LinkTo from '@/components/LinkTo';
import { SearchInput, SelectForm } from '@/components/UserForm';
import { getApplyjob } from '@/services/components/userform';
import CompanyDepart from '@/components/CompanyDepart';
import request from '@/utils/request';
import ApplyStatus from '@/components/ApplyStatus';
import { dictionaryList } from '@/services/dictionary';
import { getemployeebyrole } from '@/services/myRecruit/interview';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import { getType } from './utils';
import { offerStatus as offerStatusColors } from './colors';
import styles from './Offer.less';

const { RangePicker } = DatePicker;

const OfferList = ({ form, location, route }) => {
    const { query } = location;
    const { path } = route;
    const { getFieldDecorator } = form;
    const type = getType(path);
    const [candidateCode] = useState('');
    const [apply, setApply] = useState(null);
    const user = localStorage.getItem('user');
    const { companyId, id } = user ? JSON.parse(user) : {};
    const [visible, setVisible] = useState(false);
    const [offerStatus, setOfferStatus] = useState([]);
    const [processStatus, setProcessStatus] = useState([]);
    const [offerBtn, setOfferBtn] = useState(false);
    const [loading, setLoading] = useState(true);
    const isClickEvent = React.useRef();
    const isExpandRef = React.useRef(0);
    const getSexName = key => {
        if (key === '1') {
            return (
                <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />
            );
        }
        if (key === '2') {
            return (
                <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />
            );
        }
        return '';
    };
    const columns = [
        {
            title: '姓名',
            fixed: 'left',
            width: 150,
            dataIndex: 'talentName',
            key: 'talentName',
            render(text, record) {
                return (
                    <Fragment>
                        <LinkTo
                            onClick={async (e, url) => {
                                // 埋点
                                await eventTrack({
                                    eventName: 'personal_my_recruit_offer_detail_click',
                                    eventProps: {
                                        label: '我的offer-详情'
                                    }
                                });
                                history.push(url);
                            }}
                            to={
                                type === 'mine'
                                    ? '/personal/portal/recruit/offer/detail'
                                    : '/office/personnelManagement/recruit/offer/detail'
                            }
                            query={{
                                offerCode: record.offerCode
                            }}
                        >
                            {text}
                        </LinkTo>
                        {getSexName(record.talentSex)}
                    </Fragment>
                );
            }
        },
        {
            title: '应聘职位',
            dataIndex: 'entryPostName',
            key: 'entryPostName',
            width: 160,
            fixed: 'left'
        },
        {
            title: '公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200
        },
        {
            title: '部门',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: 200
        },
        {
            title: '手机',
            dataIndex: 'talentPhone',
            key: 'talentPhone',
            width: 160
        },
        {
            title: '邮箱',
            dataIndex: 'talentEmail',
            key: 'talentEmail',
            width: 160
        },
        {
            title: '入职时间',
            dataIndex: 'entryDate',
            sorter: () => {},
            width: 160,
            key: 'entryDate'
        },
        {
            title: 'offer流程进度',
            width: 150,
            dataIndex: 'offerProcessStatus',
            key: 'offerProcessStatus',
            filters: processStatus,
            render: (text, record) => {
                const { status } = record;
                return (
                    <div>
                        <ApplyStatus status={status} />
                        {text}
                    </div>
                );
            }
        },
        {
            title: 'offer状态',
            width: 120,
            dataIndex: 'offerState',
            key: 'offerState',
            filters: offerStatus,
            render(text, record) {
                return <span style={{ color: offerStatusColors[text] }}>{record.offerStateName || '--'}</span>;
            }
        },
        {
            title: '招聘负责',
            // width: 120,
            dataIndex: 'offerLeaderName',
            key: 'offerLeaderName'
        },
        {
            title: '操作',
            fixed: 'right',
            width: 150,
            key: 'action',
            render: (text, record) => (
                <span>
                    <LinkTo
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personal_my_recruit_offer_operator_click',
                                eventProps: {
                                    label: '我的offer-操作'
                                }
                            });
                            history.push(url);
                        }}
                        to={
                            type === 'mine'
                                ? '/personal/portal/recruit/offer/detail'
                                : '/office/personnelManagement/recruit/offer/detail'
                        }
                        query={{
                            offerCode: record.offerCode
                        }}
                    >
                        offer详情
                    </LinkTo>
                    {/* {record.entryButton && (
                        <Fragment>
                            <Divider type="vertical" />
                            <a
                                href="#"
                                onClick={e => {
                                    e.preventDefault();
                                    setCandidateCode(record.candidateCode);
                                    setVisible(true);
                                }}
                            >
                                入职
                            </a>
                        </Fragment>
                    )} */}
                </span>
            )
        }
    ];
    const formConfig = {
        baseForm: (
            <React.Fragment>
                <Form.Item label="姓名">
                    {getFieldDecorator('searchName')(<Input placeholder="请输入关键字搜索姓名" allowClear />)}
                </Form.Item>
                <Form.Item label="应聘职位">
                    {getFieldDecorator('recruitCode')(
                        <SelectForm
                            params={{ companyId }}
                            requireParam={['companyId']}
                            getData={params =>
                                getApplyjob(params).then(res => {
                                    if (res && res.code === 10000 && res.data) {
                                        return res.data || [];
                                    }
                                    return [];
                                })
                            }
                            fieldsName={{
                                selectValue: 'recruitCode',
                                selectTitle: 'recruitName'
                            }}
                            selectProps={{
                                placeholder: '请选择应聘职位',
                                allowClear: true,
                                dropdownMatchSelectWidth: false
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="公司部门" className={styles.temp}>
                    {getFieldDecorator('companyDepart', {
                        initialValue: {
                            companyId
                        }
                    })(<CompanyDepart />)}
                </Form.Item>
                <Form.Item label="手机">
                    {getFieldDecorator('talentPhone')(<Input placeholder="请输入手机" allowClear />)}
                </Form.Item>
                <Form.Item label="邮箱">
                    {getFieldDecorator('talentEmail')(<Input placeholder="请输入邮箱" allowClear />)}
                </Form.Item>
                <Form.Item label="入职时间">
                    {getFieldDecorator('date', {
                        initialValue: []
                    })(<RangePicker format="YYYY-MM-DD" />)}
                </Form.Item>
                {type === 'company' && (
                    <Form.Item label={type === 'mine' ? 'offer负责' : '招聘负责'}>
                        {getFieldDecorator('leaderIds', {
                            // initialValue:
                            //     query.candidateLeaderId &&
                            //     query.candidateLeaderId.length > 0 &&
                            //     typeof query.candidateLeaderId !== 'undefined'
                            //         ? Number(query.candidateLeaderId)
                            //         : undefined
                        })(
                            <SearchInput
                                params={{
                                    companyId,
                                    roleName: '招聘负责人'
                                }}
                                requireParam={['companyId']}
                                getData={params =>
                                    getemployeebyrole(params).then(res => {
                                        if (res && res.code === 10000) {
                                            return res.data || [];
                                        }
                                        return [];
                                    })
                                }
                                selectProps={{
                                    placeholder: '请输入',
                                    allowClear: true
                                }}
                                fieldsName={{
                                    value: 'id',
                                    title: 'employeeName',
                                    extraParams: 'userName',
                                    isBuLu: false
                                }}
                                // onChange={this.handleSelect}
                            />
                        )}
                    </Form.Item>
                )}
            </React.Fragment>
        )
    };

    const getQueryParams = ({ values, sorters, current, pageSize, filters }) => {
        const { companyDepart = {}, date = [], leaderIds, recruitCode, searchName, talentPhone, talentEmail } = values;
        let orderByField = '';
        if (sorters && sorters.field === 'entryDate') {
            const order = sorters.order === 'ascend' ? 'asc' : 'desc';
            orderByField = `entry_date ${order}`;
        }
        return {
            companyId: companyDepart.companyId || companyId,
            departmentId: companyDepart.departmentId || '',
            endTime: date[1] ? date[1].format('YYYY-MM-DD') : '',
            leaderIds: type === 'mine' ? [id] : [leaderIds].filter(item => !!item),
            orderByField,
            pageNo: current,
            pageSize,
            recruitCode,
            searchName,
            startTime: date[0] ? date[0].format('YYYY-MM-DD') : '',
            talentEmail,
            talentPhone,
            offerProcessStatus: (filters && filters.offerProcessStatus) || [],
            offerState: (filters && filters.offerState) || [],
            candidateLeaderId: type === 'mine' ? [id] : [leaderIds].filter(item => !!item)
        };
    };
    useEffect(() => {
        isExpandRef.current = query.isExpand;
    }, [query]);
    const handleReplaceRoute = data => {
        history.push({
            query: {
                ...query,
                isExpand: isExpandRef.current,
                ...data
            }
        });
    };

    // 返回Promise，数据格式：{ current: 1, pageSize: 10, data: [], total }
    const getData = async ({ filters, sorters, pageSize, current, values }) => {
        const url = type === 'mine' ? '/api/oa/v1/offer/getmyofferlist' : '/api/oa/v1/offer/getofferlist';
        const data = getQueryParams({ filters, sorters, pageSize, current, values });
        // 用以区分首次加载还是查询
        if (isClickEvent.current) {
            console.log('query', query);
            handleReplaceRoute(data);
        }
        const response = await request(url, {
            method: 'POST',
            data
        });
        if (response.code === 10000) {
            isClickEvent.current = true;
            return {
                pageSize: response.data.pageSize,
                current: response.data.pageNo,
                total: response.data.total,
                data: response.data.rows
            };
        }
        return {
            pageSize: 10,
            current: 1,
            total: 0,
            data: []
        };
    };

    const fetchApply = useCallback(async () => {
        const response = await request(`/api/oa/v1/offer/apply/${companyId}`);

        if (response.code === 10000) {
            setApply(response.data);
        } else {
            setOfferBtn(true);
        }
        setLoading(false);
    }, [companyId]);

    const handleOfferChange = fetchList => {
        setVisible(false);
        // TODO 先这样处理，后面优化
        fetchList();
    };
    // 初始化查询参数，用于 URL 参数化
    const initFields = React.useCallback(() => {
        const { startTime, endTime } = query;
        console.log('query', query);
        form.setFieldsValue({
            talentEmail: query.talentEmail || '',
            talentPhone: query.talentPhone || '',
            searchName: query.searchName || '',
            recruitCode: query.recruitCode,
            companyId: query.companyId || '',
            departmentId: query.departmentId || '',
            companyDepart: {
                companyId: query.companyId || companyId || undefined,
                departmentId: query.departmentId || undefined
            },
            date: startTime ? [moment(startTime), moment(endTime)] : '',
            leaderIds: query.leaderIds && query.leaderIds.length > 0 ? Number(query.leaderIds[0]) : undefined
        });
    }, [form]);

    useEffect(() => {
        const fetchDict = async () => {
            const response = await dictionaryList({
                codes: ['offerState', 'processStatusType']
            });

            if (response.code === 10000) {
                const group = groupBy(response.data, 'code');
                setOfferStatus(
                    group.offerState.map(item => ({
                        text: item.dictName,
                        value: item.dictValue
                    }))
                );
                setProcessStatus(
                    group.processStatusType.map(item => ({
                        text: item.dictName,
                        value: item.dictValue
                    }))
                );
            }
        };

        fetchApply();
        initFields();
        fetchDict();
    }, []);

    const extraButton = (
        <Button
            disabled={offerBtn}
            loading={loading}
            type="primary"
            onClick={async () => {
                //   埋点
                await eventTrack({
                    eventName: 'personal_my_recruit_offer_apply_click'
                });
                history.push({
                    pathname: '/personal/portal/flow/mine/list/apply',
                    query: {
                        action: 'edit',
                        formDeploymentId: apply.formDeploymentId,
                        processDeploymentId: apply.processDeploymentId,
                        templateId: apply.id,
                        templateName: apply.templateName
                    }
                });
            }}
        >
            发起offer申请
        </Button>
    );
    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" extraButton={extraButton}>
                {isPageRouter => (
                    <SimpleDataTable
                        fetchData={getData}
                        form={form}
                        formConfig={formConfig}
                        columns={columns}
                        after={fetchList =>
                            candidateCode && (
                                <QuickEntry
                                    candidateCode={candidateCode}
                                    visible={visible}
                                    onOk={() => handleOfferChange(fetchList)}
                                    onCancel={() => setVisible(false)}
                                />
                            )
                        }
                        rowKey="id"
                        cardProps={{
                            title: !isPageRouter && (type === 'mine' ? '我的offer' : 'offer管理'),
                            extra: !isPageRouter && extraButton
                        }}
                        tableProps={{
                            scroll: { x: 1730 }
                        }}
                    />
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};

OfferList.propTypes = {
    // location(props, propName, componentName) {
    //     const type = get(props[propName], 'query.type', false);
    //
    //     if (!type) {
    //         throw new Error(`查询字符串中需要传递一个 type！`);
    //     } else if (!['mine', 'company'].includes(type)) {
    //         throw new Error(
    //             `type只能为 mine（我的offer） 或者 company（offer管理）！`
    //         );
    //     }
    // }
};

OfferList.defaultProps = {
    // location: {}
};

export default withRoutePage(Form.create()(OfferList));
